#!/usr/bin/python

import functools
import os
import re
import subprocess
import threading
import pprint
import sublime
import sublime_plugin


def open_url(url):
	sublime.active_window().run_command('open_url', {"url": url})

def open_file(file_path):
	sublime.active_window().run_command('open_file', {"file": file_path})

def write_to_file(str):
	path = os.environ['TEMP']+"\\sublime_text_plugin_param.txt"
	fl = open(path, "w")
	fl.write(str)
	fl.close()
	return path

def get_out_put(cmd):
	#print(cmd)
	ret = os.popen(cmd).read()
	#print(ret)
	return ret


class OpenRequireFileCommand(sublime_plugin.TextCommand):
	def run(self, edit):
		for region in self.view.sel():
			word_region = self.view.line(region) #self.view.word(region)
			if not word_region.empty():
				word = self.view.substr(word_region)
				#pprint.pprint(word)
				path = write_to_file(word)
				rbfile_path = sublime.packages_path()+"\\User\\open_require_file.rb"
				#print(rbfile_path)
				out_str = get_out_put("ruby \"" +rbfile_path+"\" \""+path+"\"")
				print("get out str:"+out_str)
				if os.path.exists(out_str):
					driver = out_str[0]
					out_str = "/"+driver+out_str[2:]
					#print(out_str)
					open_file(out_str)
				#os.remove(path)





